package handler

import (
	"china-auto-rental/api/request"
	"china-auto-rental/internal/dao"
	"china-auto-rental/internal/models"
	"china-auto-rental/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func RegisterUser(c *gin.Context) {
	var user models.User
	var req request.RegisterUserForm

	if err := c.ShouldBind(&req); err != nil {
		return
	}

	if req.Mobile == "" || req.Password == "" || req.Image == "" {
		c.JSON(http.StatusOK, &gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	err := dao.GetOneFile(&models.User{Mobile: req.Mobile}, &user)
	if err != nil {
		c.JSON(http.StatusOK, &gin.H{
			"code": 100000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	if user.Id > 0 {
		c.JSON(http.StatusOK, &gin.H{
			"code": 100000,
			"msg":  "手机号已被使用",
			"data": nil,
		})
		return
	}

	user = models.User{
		Mobile:   req.Mobile,
		Password: pkg.Md5(req.Password),
		Image:    req.Image,
	}

	err = dao.AddFile(&user)
	if err != nil {
		c.JSON(http.StatusOK, &gin.H{
			"code": 100000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, &gin.H{
		"code": http.StatusOK,
		"msg":  "注册成功",
		"data": user.Id,
	})

}

func ListByStatusUser(c *gin.Context) {
	var req request.ListByStatusUserForm
	var user []models.User

	if err := c.ShouldBind(&req); err != nil {
		return
	}

	err := dao.GetListWhereFile(&models.User{Status: req.Status}, &user)
	if err != nil {
		c.JSON(http.StatusOK, &gin.H{
			"code": 100000,
			"msg":  "展示失败",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, &gin.H{
		"code": http.StatusOK,
		"msg":  "展示成功",
		"data": user,
	})
}

func UpdateStatusUser(c *gin.Context) {
	var req request.UpdateStatusUserForm
	var user models.User

	err := c.ShouldBind(&req)
	if err != nil {
		return
	}

	if req.Id == 0 {
		c.JSON(http.StatusOK, &gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	user = models.User{
		Id:     req.Id,
		Status: 1,
	}

	err = dao.UpdateWhereByFile(&models.User{Id: req.Id}, &user)
	if err != nil {
		c.JSON(http.StatusOK, &gin.H{
			"code": 100000,
			"msg":  "冻结失败",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, &gin.H{
		"code": http.StatusOK,
		"msg":  "冻结成功",
		"data": user.Id,
	})
}
